<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 产品管理
 *
 * @icon fa fa-circle-o
 */
class Product extends Api
{

    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * News模型对象
     * @var \app\common\model\Product
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Product;
    }
    //产品二级分类下拉
    public function secCates(){
        $productModel = new \app\common\model\Product();
        $catesArr = $productModel->query("SELECT DISTINCT(content->'$.category') AS category from fa_zz_product");
        $cates = [];
        foreach ($catesArr as $item){
            if($item && $item['category']){
                $cates[] = json_decode($item['category'],1)[1];
            }
        }
        $cates = array_values(array_unique($cates));
        $this->success('success', $cates);
    }

    /**
     * 所有数据
     *
     * @ApiMethod   (GET)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="pageNumber", type="int", required=false, description="当前页")
     * @ApiParams   (name="pageSize", type="int", required=false, description="分页大小")
     * @ApiParams   (name="secCate", type="string", required=false, description="二级分类")
     * @ApiParams   (name="name", type="string", required=false, description="产品名称")
     * */
    public function pageList()
    {
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        $secCate = $this->request->request("secCate");
        $name = $this->request->request("name");
        $where = ['status'=>'normal'];
        $whereObj = Db::name('zz_product');
        $whereCountObj =  Db::name('zz_product');//$whereObj查询后会重置where条件  用这种方式解决
        if(!empty($secCate)){
            $whereObj->where("content->'$.category' like '%{$secCate}%'");
            $whereCountObj->where("content->'$.category' like '%{$secCate}%'");
        }
        if(!empty($name)){
            $whereObj->where("content->'$.product_name' COLLATE utf8mb4_general_ci like '%{$name}%'");
            $whereCountObj->where("content->'$.product_name' COLLATE utf8mb4_general_ci like '%{$name}%'");
        }

        $list = $whereObj->page($page,$pagesize)->select();
        $total = $whereCountObj->count();

        $this->success('success', ['list' => $list, 'total' => $total]);
    }

    /**
     * 新增
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="type", type="int", required=true, description="类型 0-成卷线材 1-异形线材")
     * @ApiParams   (name="content", type="string", required=true, description="内容，json格式")
     *
     */
    public function add()
    {
        $param = $this->request->post(false);
        $param['status'] = 'normal';
        if(!$param['type']){
            $param['type'] = 0;
        }
        $ret = $this->model->save($param);
        if ($ret) {
            $this->success('success', $this->model->getLastInsID());
        } else {
            $this->error($this->model->getError());
        }
    }

    /**
     * 编辑
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="产品id")
     * @ApiParams   (name="content", type="string", required=true, description="内容，json格式")
     *
     */
    public function edit()
    {
        $param = $this->request->post(false);
        $id = $param['id'];
        if (!$id) {
            $this->error(__('id错误'));
        }
        $product = $this->model->find(['id'=>$id]);
        if (!$product) {
            $this->error(__('数据不存在'));
        }
        $product['content'] = $param['content'];
        $ret = $this->model->update($param,['id'=>$id]);
        if ($ret) {
            $this->success('success', $product);
        } else {
            $this->error($this->model->getError());
        }
    }

    /**
     * 详情
     *
     * @ApiMethod   (GET)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="产品id")
     *
     */
    public function detail()
    {
        $id = $this->request->get('id',0);
        if (!$id) {
            $this->error(__('id错误'));
        }
        $product = $this->model->find(['id'=>$id]);
        if (!$product) {
            $this->error(__('数据不存在'));
        }
        $this->success('success', $product);
    }

    /**
     * 删除
     *
     * @ApiMethod   (DELETE)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="产品id")
     *
     */
    public function del()
    {
        $id = $this->request->param('id',0);
        if (!$id) {
            $this->error(__('id错误'));
        }
        $product = $this->model->find(['id'=>$id]);
        if (!$product) {
            $this->error(__('数据不存在'));
        }
        $this->success('success', $this->model->where('id',$id)->delete());
    }

    /**
     * 转译-其他语言转译中文
     *
     * @ApiMethod   (GET)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="产品id")
     *
     */
    public function trans()
    {
        set_time_limit(0);
        ini_set('max_execution_time', '0');
        $id = $this->request->get('id',0);
        if (!$id) {
            $this->error(__('id错误'));
        }
        $product = $this->model->find(['id'=>$id]);
        if (!$product) {
            $this->error(__('数据不存在'));
        }


        $lan_target = 'zh'; //报文原始语言
        $lan_source = 'zh'; //翻译的目标语言
        switch ($product['language']){
            case '日本':
                $lan_source = 'ja';
                break;
            case '欧洲标准89':
                $lan_source = 'de';
                break;
            case 'iso105':
            case '美国标准':
                $lan_source = 'en';
                break;

        }
        $content = json_decode(preg_replace('/[\x00-\x1F]/','', $product['content']),1);
        //本语言不需要翻译
        if($lan_target == $lan_source){
            $product['content_zh'] = json_encode($content, JSON_UNESCAPED_UNICODE);
            $product->save();
//            $this->model->update($product);
            $this->success('success', $product);
        }
//            print_r($content);die;
//            continue;
        if (json_last_error() != JSON_ERROR_NONE) {
            // 处理错误，可以根据错误类型提供相应的处理方式
            $this->error( "JSON 解析出错: " . json_last_error_msg());
        }
        $en_content = $content;
        $en_content['product_name'] =translate($content['product_name'], $lan_source, $lan_target);
        foreach ($en_content['category'] as $k => $v) {
//            $en_content['category'][$k] =translate($v, $lan_source, $lan_target);
            //只翻译二级分类（一级分类不用、三级分类翻译后不准确，原样展示）
            if($k == 1){
                $en_content['category'][$k] = translate($v, $lan_source, $lan_target);
            }
        }
        foreach ($en_content['banner'] as $k => &$v) {
            if(isset($v['des'])){
                $v['des'] =translate($v['des'], $lan_source, $lan_target);
            }
            if(isset($v['title'])){
                $v['title'] =translate($v['title'], $lan_source, $lan_target);
            }
        }
        foreach ($en_content['attributes'] as $k => &$v) {
            if(isset($v['name'])){
                $v['name'] =translate($v['name'], $lan_source, $lan_target);
            }
            if(isset($v['value'])){
                $v['value'] =translate($v['value'], $lan_source, $lan_target);
            }

        }
        if(isset($en_content['detail']['des'])){
            $en_content['detail']['des'] =translate($en_content['detail']['des'], $lan_source, $lan_target);
        }

        foreach ($en_content['detail']['paragraph'] as &$vv) {
            if (isset($vv['title'])) {
                $vv['title'] =translate($vv['title'], $lan_source, $lan_target);
            }
            foreach ($vv['attributes'] as &$vvv) {
                if (isset($vvv['name'])) {
                    $vvv['name'] =translate($vvv['name'], $lan_source, $lan_target);
                }
                if (isset($vvv['value'])) {
                    $vvv['value'] =translate($vvv['value'], $lan_source, $lan_target);
                }
            }
            if (isset($vv['banner']['title'])) {
                $vv['banner']['title'] =translate($vv['banner']['title'], $lan_source, $lan_target);
            }
        }
        foreach ($en_content['technical']['process'] as $k=>&$v){
            if(isset($v['des'])){
                $v['des'] =translate($v['des'],$lan_source,$lan_target);
            }
            if(isset($v['title'])){
                $v['title'] =translate($v['title'],$lan_source,$lan_target);
            }
        }
        foreach ($en_content['technical']['information'] as $k=>&$v){
            if(isset($v['title'])){
                $v['title'] =translate($v['title'],$lan_source,$lan_target);
            }
            foreach ($v['content'] as $kk=>&$vv){
                if(isset($vv['title'])){
                    $vv['title'] =translate($vv['title'],$lan_source,$lan_target);
                }
                if(isset($vv['des'])){
                    $vv['des'] =translate($vv['des'],$lan_source,$lan_target);
                }
                if(isset($vv['tips'])){
                    $vv['tips'] = translate($vv['tips'],$lan_source,$lan_target);
                }
            }
        }
//            $product['content'] = json_encode($product['content'], JSON_UNESCAPED_UNICODE);
//            $product['content_en'] = json_encode($en_content, JSON_UNESCAPED_UNICODE);
        //编码转换
        // 检查数据是否为UTF-8编码
        if (!mb_check_encoding($en_content, 'UTF-8')) {
            // 如果不是UTF-8编码，则转换为UTF-8
            $en_content = mb_convert_encoding( $en_content, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5' );
        }
        $product['content_zh'] = json_encode($en_content, JSON_UNESCAPED_UNICODE);
        if (json_last_error() != JSON_ERROR_NONE) {
            // 处理错误，可以根据错误类型提供相应的处理方式
            $this->error( "JSON 解析出错2: " . json_last_error_msg());
        }
//        $this->model->update($product);
        $product->save();
        $this->success('success', $product);
    }
}
